package com.yuneec.droneservice.command;

import com.yuneec.droneservice.model.PackageInfo;
import com.yuneec.droneservice.request.IResponse;
import com.yuneec.droneservice.utils.ByteUtils;

/**
 * Created by gjw on 2017/3/27.
 */

public class StartUpdate extends BaseCommand {

    public StartUpdate(PackageInfo packageInfo) {
        super(MAV_RC_COMMAND.MAV_RC_CMD_START_UPDATE);
        byte[] bytes1 = packageInfo.getHardwareVersion().getBytes();
        byte[] bytes2 = packageInfo.getFirmwareVersion().getBytes();
        byte[] bytes3 = packageInfo.getMcuVersion().getBytes();
        byte[] bytes4 = packageInfo.getFilename().getBytes();
        //add u32 fileSize  by zzd
        long fileSize = packageInfo.getFileSize();
        byte[] bytes5 = new byte[4];
        bytes5[0] = (byte) (fileSize & 0xFF);
        bytes5[1] = (byte) ((fileSize >> 8) & 0xFF);
        bytes5[2] = (byte) ((fileSize >> 16) & 0xFF);
        bytes5[3] = (byte) ((fileSize >> 24) & 0xFF);

        byte[] bytes6 = packageInfo.getType().getBytes();
        data = new byte[10 + bytes1.length + bytes2.length + bytes3.length + bytes4.length + bytes5.length + bytes6.length];
        ByteUtils.uShortToByteArray(data, 0, bytes1.length, IS_BIGENDIAN);
        System.arraycopy(bytes1, 0, data, 2, bytes1.length);

        ByteUtils.uShortToByteArray(data, 2 + bytes1.length, bytes2.length, IS_BIGENDIAN);
        System.arraycopy(bytes2, 0, data, 4 + bytes1.length, bytes2.length);

        ByteUtils.uShortToByteArray(data, 4 + bytes1.length + bytes2.length, bytes3.length, IS_BIGENDIAN);
        System.arraycopy(bytes3, 0, data, 6 + bytes1.length + bytes2.length, bytes3.length);

        ByteUtils.uShortToByteArray(data, 6 + bytes1.length + bytes2.length + bytes3.length, bytes4.length, IS_BIGENDIAN);


        System.arraycopy(bytes4, 0, data, 8 + bytes1.length + bytes2.length + bytes3.length, bytes4.length);

        System.arraycopy(bytes5, 0, data, 8 + bytes1.length + bytes2.length + bytes3.length + bytes4.length, bytes5.length);


        ByteUtils.uShortToByteArray(data, 8 + bytes1.length + bytes2.length + bytes3.length + bytes4.length + bytes5.length, bytes6.length, IS_BIGENDIAN);

        System.arraycopy(bytes6, 0, data, 10 + bytes1.length + bytes2.length + bytes3.length + bytes4.length + bytes5.length, bytes6.length);
    }


    @Override
    public IResponse toResponse(byte[] data, int off, int len) {
        int code = data[off + 1] & 0xff;
        return new IResponse(ids(), code);
    }
}
